package com.meilingcloud.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilingcloud.common.constant.UserConstants;
import com.meilingcloud.system.domain.SysCustomForm;
import com.meilingcloud.system.mapper.SysCustomFormMapper;
import com.meilingcloud.system.service.ISysCustomFormService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义单 Service业务层处理
 *
 * @author chenl
 * @date 2021-01-29
 */
@Service
public class SysCustomFormServiceImpl extends ServiceImpl<SysCustomFormMapper, SysCustomForm> implements ISysCustomFormService {

    @Override
    public List<SysCustomForm> queryList(SysCustomForm sysCustomForm) {
        LambdaQueryWrapper<SysCustomForm> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(sysCustomForm.getFormKey())) {
            lqw.eq(SysCustomForm::getFormKey, sysCustomForm.getFormKey());
        }
        if (StringUtils.isNotBlank(sysCustomForm.getFormType())) {
            lqw.eq(SysCustomForm::getFormType, sysCustomForm.getFormType());
        }
        if (StringUtils.isNotBlank(sysCustomForm.getFormName())) {
            lqw.like(SysCustomForm::getFormName, sysCustomForm.getFormName());
        }
        return this.list(lqw);
    }

    @Override
    public String checkFormKeyUnique(SysCustomForm sysCustomForm) {
        Long formId = ObjectUtil.isNull(sysCustomForm.getFormId()) ? -1L : sysCustomForm.getFormId();
        SysCustomForm customForm = baseMapper.selectOne(new QueryWrapper<SysCustomForm>().eq("form_key", sysCustomForm.getFormKey()));
        if (ObjectUtil.isNotNull(customForm) && !customForm.getFormId().equals(formId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public SysCustomForm getByKey(String formKey) {
        return this.getOne(new LambdaQueryWrapper<SysCustomForm>().eq(SysCustomForm::getFormKey, formKey).last("limit 1"));
    }

    @Override
    public Map<String, List<String>> formDataShow(String formKey) {
        Map<String, List<String>> map = new HashMap<>();
        if (StringUtils.isBlank(formKey)) {
            return map;
        }
        SysCustomForm customForm = this.getByKey(formKey);
        if (customForm != null) {
            map.put(formKey, Collections.singletonList(customForm.getFormJson()));
        } else {
            map.put(formKey, null);
        }
        return map;
    }
}
